package org.bonorsoft.modules.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.aspect.annotation.PermissionData;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.bonorsoft.common.system.dataquery.DataQueryGenerator;
import org.bonorsoft.common.system.vo.Ztree;
import org.bonorsoft.common.util.StringUtils;
import org.bonorsoft.modules.user.entity.MobileDepart;
import org.bonorsoft.modules.user.entity.MobileRole;
import org.bonorsoft.modules.user.service.IMobileDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/mobile/dept")
public class MobileDepartController extends BonorController<MobileDepart, IMobileDepartService> {
    private String prefix = "mobile/dept";
    @Autowired
    private IMobileDepartService mobileDepartService;

    @RequiresPermissions("mobile:dept:view")
    @GetMapping()
    public String dept() {
        return prefix + "/dept";
    }

    /**
     * 分页列表查询
     *
     * @param mobileDepart
     * @param req
     * @return
     */
    @PostMapping(value = "/list")
    @RequiresPermissions("mobile:dept:list")
    @PermissionData(value = "single")
    @ResponseBody
    public List<MobileDepart> queryPageList(MobileDepart mobileDepart, HttpServletRequest req) {
        QueryWrapper<MobileDepart> queryWrapper = DataQueryGenerator.initQueryWrapper(mobileDepart, req);
        queryWrapper.orderByAsc("order_num");
        return mobileDepartService.list(queryWrapper);

    }

    /**
     * 新增部门
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) {
        mmap.put("dept", mobileDepartService.getById(parentId));
        return prefix + "/add";
    }

    /**
     * 选择部门树
     */
    @GetMapping("/selectDeptTree/{deptId}")
    public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap mmap) {
        mmap.put("dept", mobileDepartService.getById(deptId));
        return prefix + "/tree";
    }

    /**
     * 添加
     *
     * @param mobileDepart
     * @return
     */
    @AutoLog(value = "组织结构-添加")
    @RequiresPermissions("system:dept:add")
    @PostMapping(value = "/add")
    @ResponseBody
    public Result<?> add(@Validated MobileDepart mobileDepart) {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(mobileDepartService.checkDeptNameUnique(mobileDepart))) {
            return Result.error("新增部门'" + mobileDepart.getDeptName() + "'失败，部门名称已存在");
        }
        mobileDepartService.save(mobileDepart);
        return Result.ok("添加成功！");
    }

    /**
     * 修改
     */
    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) {
        MobileDepart dept = mobileDepartService.getById(deptId);
        if (StringUtils.isNotNull(dept) && 100L == deptId) {
            mmap.put("parentName", "无");
        }
        String parentName = mobileDepartService.getDepartNameById(dept.getParentId()).getDeptName();
        mmap.put("parentName", parentName);
        mmap.put("dept", dept);
        return prefix + "/edit";
    }

    /**
     * 编辑
     *
     * @param mobileDepart
     * @return
     */
    @AutoLog(value = "组织结构-编辑")
    @RequiresPermissions("mobile:dept:edit")
    @PostMapping(value = "/edit")
    @ResponseBody
    public Result<?> edit(@Validated MobileDepart mobileDepart) {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(mobileDepartService.checkDeptNameUnique(mobileDepart))) {
            return Result.error("修改部门'" + mobileDepart.getDeptName() + "'失败，部门名称已存在");
        } else if (mobileDepart.getParentId().equals(mobileDepart.getDeptId())) {
            return Result.error("修改部门'" + mobileDepart.getDeptName() + "'失败，上级部门不能是自己");
        }
        mobileDepartService.updateDept(mobileDepart);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param deptId
     * @return
     */
    @AutoLog(value = "组织结构-通过id删除", operateType = 4)
    @RequiresPermissions("mobile:dept:remove")
    @DeleteMapping(value = "/remove/{deptId}")
    @ResponseBody
    public Result<?> remove(@PathVariable("deptId") Long deptId) {
        if (mobileDepartService.selectDeptCount(deptId) > 0) {
            return Result.error("存在下级部门,不允许删除");
        }
        if (mobileDepartService.checkDeptExistUser(deptId)) {
            return Result.error("部门存在用户,不允许删除");
        }
        mobileDepartService.removeById(deptId);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "组织结构-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mobileDepartService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "组织结构-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MobileDepart mobileDepart = mobileDepartService.getById(id);
        return Result.ok(mobileDepart);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mobileDepart
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MobileDepart mobileDepart) {
        return super.exportXls(request, mobileDepart, MobileDepart.class, "组织结构");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MobileDepart.class);
    }

    /**
     * 加载部门列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    @PermissionData(value = "single")
    public List<Ztree> treeData(HttpServletRequest req) {
        List<Ztree> ztrees = mobileDepartService.selectDeptTree(new MobileDepart(), req);
        return ztrees;
    }

    /**
     * 加载角色部门（数据权限）列表树
     */
    @GetMapping("/roleDeptTreeData")
    @ResponseBody
    public List<Ztree> deptTreeData(MobileRole role, HttpServletRequest request) {
        List<Ztree> ztrees = mobileDepartService.roleDeptTreeData(role, request);
        return ztrees;
    }

    /**
     * 校验部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public String checkDeptNameUnique(MobileDepart dept) {
        return mobileDepartService.checkDeptNameUnique(dept);
    }

}
